package missionLog;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import RofMission.RofMissionParams;

public class MissionLog {
	private Path reportPath=null;
	private String missionName="";
	private BufferedWriter logWriter=null;
	
	public MissionLog (RofMissionParams params) throws IOException {
		this.missionName=params.getMissionLog();
		processFiles(params);

	}
	
	/**
	 * Generate the list of filename from the mission name
	 * @return list of string, each element is a mission filename
	 * @throws IOException 
	 */
	public List<String> findFiles() throws IOException {
		
		List<String> result= new ArrayList<String>();
		Path missionPath = Paths.get(missionName);
		String fileName= missionPath.getFileName().toString();
		Path missionDirPath= missionPath.getParent();
		String template=fileName.replace("[0]", "*");
		try (DirectoryStream<Path> stream = Files.newDirectoryStream(missionDirPath,template)) {
		      for (Path entry : stream) {
		        result.add(entry.toString());
		      }
		}
		return result;
	}
	
	
	/**
	 * Analyze a mission log file => print in report log file the planes crashed
	 * @param fileName
	 * @throws IOException
	 */
	private void processFile(String fileName) throws IOException {
		Path filePath = Paths.get(fileName);
		Hashtable<String, String> planeNames= new Hashtable<String, String>();
		 try (BufferedReader reader = Files.newBufferedReader(filePath,StandardCharsets.UTF_8)) {
			 String line = null;
			 int count=0;
		      while ((line = reader.readLine()) != null) {
		        if (line.contains("AType:12") &&  ( line.contains("Takeoff_") || line.contains("Land_"))) {
		        		// bot plane declaration
		        		int i = line.indexOf("NAME:");
		        		int j= line.indexOf("PID:");
		        		String planeName=line.substring(i+5, j-1);
		        		i = line.indexOf("ID:");
		        		j= line.indexOf("TYPE:");
		        		String planeID=line.substring(i+3, j-1);
		        		planeNames.put(planeID, planeName);
		        }

		      if (line.contains("AType:3") ||  line.contains("AType:2")) {
		    	 //entity destroyed => if plane write it in report file
		    	  String event="crashed";
		    	  if (line.contains("AType:2")) event="damaged";
		    	  //find time
		    	  System.out.println(line);
		    	  int i = line.indexOf("T:");
		    	  int j= line.indexOf("AType");		    	  
		    	  String timeString=line.substring(i+2, j-1);
		    	  int timeSec=Integer.parseInt(timeString)/50;
		    	  
		    	  //find Position
		    	  i = line.indexOf("POS(");
		    	  j= line.indexOf(")");
		    	  String position=line.substring(i+4, j-1);	   
		    	  
		    	  //find plane ID
		    	  i = line.indexOf("TID:");
		    	  j= line.indexOf("POS");
		    	  String planeID=line.substring(i+4, j-1);
		    	  String planeName=planeNames.get(planeID);
		    	  if (planeName != null) {
		    		  logWriter.write("Time: "+timeSec+"(s): Plane \""+planeName+"\" "+event+" at ("+position+")!\n");
		    		  count++;
		    	  }
		      }
		   }  
		 }
		 
	}
	
	/**
	 * Create and open report file
	 * @throws IOException
	 */
	private void createReport(RofMissionParams params) throws IOException {
		Path filePath = Paths.get(params.getReportfileName());
		if (!Files.exists(filePath)) {
			Files.createFile(filePath);
		}
		BufferedWriter logWriter = Files.newBufferedWriter(filePath, StandardCharsets.ISO_8859_1);
		this.logWriter=logWriter;
	
	}
	
	/**
	 * close report file
	 * @throws IOException
	 */
	private void closeReport() throws IOException {
		if (logWriter != null) logWriter.close();
	}
	
	/**
	 * process all mmission logs files
	 * @throws IOException
	 */
	public void processFiles(RofMissionParams params) throws IOException {
		createReport(params);
		logWriter.write("Parsing Rof Log files...\n");
		List<String> files = findFiles();
		for (String file: files) {
			processFile(file);
		}
		closeReport();
	}
}
